﻿//
// Copyright 2024 Exhunter Technology Co.Ltd2.
//

using System;
using System.Text;

namespace X18.Framework.Core.Hash
{
    /// <summary>
    /// 字节类型转换工具
    /// </summary>
    public static class BitConverter
    {
        public static string ToString(byte[] value)
        {
            if (value == null)
                throw new ArgumentNullException();
            return ToString(value, 0, value.Length);
        }

        public static string ToString(byte[] value, int startIndex)
        {
            if (value == null)
                throw new ArgumentNullException();
            return ToString(value, startIndex, value.Length - startIndex);
        }

        public static string ToString(byte[] value, int startIndex, int length)
        {
            if (value == null)
                throw new ArgumentNullException();
            if (startIndex < 0 || startIndex >= value.Length && startIndex > 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException();
            }
            if (startIndex > value.Length - length)
            {
                throw new ArgumentException();
            }
            if (length == 0)
            {
                return string.Empty;
            }
            // (int.MaxValue / 3) == 715,827,882 Bytes == 699 MB
            if (length > int.MaxValue / 3)
            {
                throw new ArgumentOutOfRangeException();
            }
            var dst = new StringBuilder(length * 2);
            for (int i = startIndex; i < length; i++)
            {
                byte b = value[i];
                dst.AppendFormat("{0,2:x2}", b);
            }

            return dst.ToString();
        }
    }
}
